﻿unit EventRepFrm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, DBGridEh, GridsEh, JvFormPlacement, JvComponentBase,
  cxGridExportLink,
  dxRibbonForm,DateUtils,
  JvAppStorage, JvAppIniStorage, ExtCtrls, StdCtrls, Mask, DBCtrlsEh,
  DBLookupEh, ComCtrls, JvExControls, JvXPCore, JvXPBar, DB, FIBDataSet,
  pFIBDataSet, ImgList, cxGraphics, dxSkinsCore, dxSkinSeven, cxControls,
  cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
  cxDBLookupEdit, cxDBLookupComboBox, cxCalendar, cxStyles, dxSkinscxPCPainter,
  cxCustomData, cxFilter, cxData, cxDataStorage, cxDBData,
  cxGridCustomPopupMenu, cxGridPopupMenu, cxGridCustomTableView,
  cxGridTableView, cxGridBandedTableView, cxGridDBBandedTableView,
  cxGridCustomView, cxClasses, cxGridLevel, cxGrid, ProgresFrm,
  dxSkinsdxRibbonPainter, dxRibbon, JvDialogs, dxSkinMcSkin, cxLookAndFeels,
  cxLookAndFeelPainters, cxPropertiesStore, cxSplitter, dxSkinOffice2010Blue,
  dxSkinOffice2010Silver, dxSkinOffice2010Black;

type
  TEventRepForm = class(Tdxcustomribbonform)
    Panel1: TPanel;
    JvXPBar1: TJvXPBar;
    Panel2: TPanel;
    GroupBox1: TGroupBox;
    Label2: TLabel;
    Label3: TLabel;
    IsPrincipal: TCheckBox;
    IsCollector: TCheckBox;
    JvXPBar2: TJvXPBar;
    JvXPBar3: TJvXPBar;
    JvAppIniFileStorage1: TJvAppIniFileStorage;
    JvFormStorage1: TJvFormStorage;
    Panel3: TPanel;
    InfoPanel: TPanel;
    KDS: TpFIBDataSet;
    KSource: TDataSource;
    CSource: TDataSource;
    CDS: TpFIBDataSet;
    ADS: TpFIBDataSet;
    ASource: TDataSource;
    MDS: TpFIBDataSet;
    MSource: TDataSource;
    DS: TpFIBDataSet;
    RDS: TpFIBDataSet;
    RSource: TDataSource;
    Source: TDataSource;
    UDS: TpFIBDataSet;
    USource: TDataSource;
    Splitter2: TSplitter;
    NoteBar: TJvXPBar;
    Note: TMemo;
    Panel4: TPanel;
    Panel6: TPanel;
    Label1: TLabel;
    Label4: TLabel;
    D_1: TDateTimePicker;
    D_2: TDateTimePicker;
    CGrid: TDBGridEh;
    StateIL: TImageList;
    DSource: TDataSource;
    D: TpFIBDataSet;
    CDSTP: TFIBSmallIntField;
    CDSD: TFIBDateField;
    CDST: TFIBTimeField;
    CDSNAME: TFIBStringField;
    CDSPSUM: TFIBBCDField;
    CDSRSUM: TFIBBCDField;
    CDSSALDO: TFIBBCDField;
    CDSANSWER: TFIBStringField;
    CDSSTATE: TFIBSmallIntField;
    CDSETYPE: TFIBStringField;
    CDSRTYPE: TFIBStringField;
    CDSNOTE: TFIBStringField;
    CDSSDATE: TFIBDateTimeField;
    CDSEDATE: TFIBDateTimeField;
    CDSECODE: TFIBStringField;
    CDSACODE: TFIBStringField;
    RType: TComboBox;
    cbb_kontr: TcxLookupComboBox;
    dt1: TcxDateEdit;
    dt2: TcxDateEdit;
    cbb_collect: TcxLookupComboBox;
    l1: TcxGridLevel;
    grd1: TcxGrid;
    v1: TcxGridDBBandedTableView;
    clv1SDATE: TcxGridDBBandedColumn;
    clv1DACTIVE: TcxGridDBBandedColumn;
    clv1TACTIVE: TcxGridDBBandedColumn;
    clv1LTIME: TcxGridDBBandedColumn;
    clv1CODE: TcxGridDBBandedColumn;
    clv1ACCCODE: TcxGridDBBandedColumn;
    clv1MASTER: TcxGridDBBandedColumn;
    clv1Street: TcxGridDBBandedColumn;
    clv1STREETNAME: TcxGridDBBandedColumn;
    clv1HOUSE: TcxGridDBBandedColumn;
    clv1FLAT: TcxGridDBBandedColumn;
    clv1KONTRAGENTNAME: TcxGridDBBandedColumn;
    clv1Collector: TcxGridDBBandedColumn;
    clv1CollectorName: TcxGridDBBandedColumn;
    clv1STATE: TcxGridDBBandedColumn;
    clv1ETYPE: TcxGridDBBandedColumn;
    clv1ETYPENAME: TcxGridDBBandedColumn;
    clv1ERESULT: TcxGridDBBandedColumn;
    clv1RTYPENAME: TcxGridDBBandedColumn;
    clv1NOTE: TcxGridDBBandedColumn;
    clv1SUMMA: TcxGridDBBandedColumn;
    clv1SRV: TcxGridDBBandedColumn;
    clv1KONTRAGENT: TcxGridDBBandedColumn;
    clRCOLLECTOR: TcxGridDBBandedColumn;
    clRCOLLECTORNAME: TcxGridDBBandedColumn;
    ppm1: TcxGridPopupMenu;
    dlg1: TJvSaveDialog;
    RibbonTab1: TdxRibbonTab;
    Ribbon: TdxRibbon;
    prop1: TcxPropertiesStore;
    cxspltr1: TcxSplitter;
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure JvXPBar2Click(Sender: TObject);
    procedure SourceDataChange(Sender: TObject; Field: TField);
    procedure DSourceDataChange(Sender: TObject; Field: TField);
    procedure GridEnter(Sender: TObject);
    procedure CGridEnter(Sender: TObject);
   procedure PrintData(AGrid: TDBGridEh; F: TField; Rect: TRect;
          BColor, FColor: TColor; Align: cardinal; Bold: boolean = false);
    procedure CGridDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumnEh; State: TGridDrawState);
    procedure JvXPBar3Click(Sender: TObject);
    procedure v1CellClick(Sender: TcxCustomGridTableView;
      ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
      AShift: TShiftState; var AHandled: Boolean);
    procedure v1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FormActivate(Sender: TObject);
  private
    Progres: TProgresForm;
    StartTime: TDateTime;
    procedure OpenDataSet;
    procedure SetNote;
    procedure MakeFullList;
    procedure prShow(show :Boolean; mes :string='Получаем данные');
  public
    { Public declarations }
  end;

var
  EventRepForm: TEventRepForm;

implementation
 uses  NameFrm, SrvSaveListFrm, {GridToXLS,} SrvFltUnit, DModule,
  cmUtils;

{$R *.dfm}

procedure TEventRepForm.PrintData(AGrid: TDBGridEh; F: TField; Rect: TRect;
          BColor, FColor: TColor; Align: cardinal; Bold: boolean = false);
   var S: string;
  begin
   if F=nil then Exit;
   if F.DataType=ftTime then S:=' '+FormatDateTime('HH:MM',F.AsDateTime)
   else if F.DataType=ftBCD then
     if F.AsCurrency<>0 then S:=FormatFloat('#,##0.00',F.AsCurrency)+' '
                        else S:=''
   else S:=' '+F.AsString;
   AGrid.Canvas.Brush.Color:=BColor;
   AGrid.Canvas.Font.Color:=FColor;
   if Bold then AGrid.Canvas.Font.Style := AGrid.Canvas.Font.Style + [fsBold];
   AGrid.Canvas.FillRect(Rect);
   DrawText(AGrid.Canvas.Handle, PChar(S),Length(S),Rect,
            Align);
  end;

procedure TEventRepForm.CGridDrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumnEh; State: TGridDrawState);
 var F: TField;

 procedure PrintName;
  var TP: integer;
  begin //наименование ктивного события
   TP:=D.FN('TP').AsInteger;
   case TP of
    2: PrintData(CGrid, F, Rect, clWhite, clNavy, DT_LEFT, true);
    3: PrintData(CGrid, F, Rect, clInfoBk, clBlack, DT_LEFT);
    4: PrintData(CGrid, F, Rect, clCream, clMaroon, DT_LEFT);
    5: PrintData(CGrid, F, Rect, clMoneyGreen, clNavy, DT_LEFT, True);
   end;
  end;

 procedure PrintAnswer;
  var TP: integer;
  begin
   TP:=D.FN('TP').AsInteger;
   case TP of
    3: PrintData(CGrid, F, Rect, clInfoBk, clBlack, DT_LEFT);
    4: if F.FieldName='ANSWER' then PrintData(CGrid, F, Rect, clCream, clGreen, DT_LEFT)
                               else PrintData(CGrid, F, Rect, clCream, clMaroon, DT_LEFT);
    5: PrintData(CGrid, F, Rect, clMoneyGreen, clNavy, DT_LEFT, true);
   end;
  end;

 procedure PrintRSum;
  var TP: integer;
  begin //наименование ктивного события
   TP:=D.FN('TP').AsInteger;
   case TP of
    2: PrintData(CGrid, F, Rect, clWhite, clRed, DT_RIGHT, true);
    3,4,5: PrintData(CGrid, F, Rect, clAqua, clNavy, DT_RIGHT, true);
   end;
  end;

begin
 if F=nil then Exit;
 if not (gdSelected in State) or not (gdFocused in State) then //только неактивные ячейки
  begin
   F:=Column.Field;
   if (F.FieldName='NAME') then
     PrintName //печать наименованиея активного события
   else if (F.FieldName='RSUM') and (F.AsCurrency<>0) then
     PrintRSum
   else if (F.FieldName<>'TP') then PrintAnswer;
  end;
end;

procedure TEventRepForm.CGridEnter(Sender: TObject);
begin
 SetNote;
end;

procedure TEventRepForm.DSourceDataChange(Sender: TObject; Field: TField);
begin
 SetNote;
end;

procedure TEventRepForm.FormActivate(Sender: TObject);
begin
  SetTabActive('rep',True);
end;

procedure TEventRepForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
 RemoveBtn(Name);
 Action:=caFree;
end;

procedure TEventRepForm.FormCreate(Sender: TObject);
begin
 AddButton(self);
 KDS.Open; CDS.Open;
 //ADS.Open; MDS.Open; RDS.Open; UDS.Open;
 //InitGrids(Self);
 //Kontragent.SelectNextValue(true);
 //Collector.SelectNextValue(true);

  prop1.StorageName:=ExtractFilePath(Application.ExeName)+'config\EventRepForm';
  prop1.RestoreFrom;

end;

procedure TEventRepForm.GridEnter(Sender: TObject);
begin
 //SetNote;
end;

procedure TEventRepForm.JvXPBar2Click(Sender: TObject);
var
  day :Integer;
begin
 day:= DaysBetween(dt1.Date, dt2.Date);
 if day>60 then
 begin
  if MessageDlg('Вы действительно хотите сформировать отчет за' + #13#10 +
                '                '+DateName(day)+
                ' ?',  mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
     OpenDataSet;
  end else Exit;
 end else OpenDataSet;


end;

procedure TEventRepForm.JvXPBar3Click(Sender: TObject);
begin
 //SaveAsExcel(Grid, nil, '');
 //ShowMessage(IntToStr(cbb_kontr.ItemIndex));
 if dlg1.Execute then
 ExportGridToExcel(dlg1.FileName,grd1,true,True,True,'xls');
end;

procedure TEventRepForm.prShow(show :Boolean; mes :string='Получаем данные');
begin
 if show=true then
 begin
   Progres:=TProgresForm.Create(Application);
   Progres.edt1.Text:='Получаем данные';
   Progres.Show;
   Progres.btn1.Visible:=true;
   Progres.disc:='C:';
   Progres.StartTime;
   Application.ProcessMessages;
 end else
 begin
  Progres.Close;
  Progres.Free;
 end;
end;

procedure TEventRepForm.MakeFullList;
 var AccCode: string;
begin
 if DS.IsEmpty then AccCode:=''
               else AccCode:=DS.FN('AccCode').AsString;
 D.Close;
 if AccCode='' then Exit;
 D.ParamByName('AccCode').AsString:=AccCode;
 D.ParamByName('D1').AsDate:=D_1.Date;
 D.ParamByName('D2').AsDate:=D_2.Date;
 D.ParamByName('List').AsString:=DS.FN('Srv').AsString;
 //prShow(True);
  Screen.Cursors[5]:=LoadCursorFromFile
                  (PWideChar(ExtractFilePath(Application.ExeName)+'common\busy.ani'));
  Screen.Cursor := 5;
  Application.ProcessMessages;
 D.Open;
  Screen.Cursor:=crDefault;
 //prShow(False);
 D.Last;
end;

procedure TEventRepForm.OpenDataSet;
 var S,sql,clause: string;
  kont,collect :Integer;
begin
 StartTime:=Now;
 clause:='';
 sql:='select E.CODE, E.STATE, E.ETYPE, SE.NAME ETYPENAME, SR.NAME RTYPENAME,'+
      ' E.SDATE, iif(E.ERESULT = '+#39+#39+', null, E.LASTTIME) LTIME, E.lasttime,'+
      ' SS.MASTER, ST.CODE STREET,'+
      ' ST.NAME STREETNAME,'+
      ' SA.HOUSE, SA.FLAT, E.DACTIVE, E.TACTIVE,E.ERESULT,'+
      ' iif(E.ERESULT = '+#39+#39+', null, E.ERESULT) ERESULT, E.NOTE, E.SUMMA, E.ETIME,'+
      ' E.ACCCODE, E.USR COLLECTOR, SU.NAME COLLECTORNAME, E.RUSR RCOLLECTOR,'+
      ' SUR.NAME RCOLLECTORNAME, E.KONTRAGENT, SK.NAME KONTRAGENTNAME, SK.SRV'+
      ' from EVENTS E'+
      ' left join SPR$SCHET SS on (SS.CODE = E.ACCCODE)'+
      ' left join SPR$ADDR SA on (SA.CODE = SS.ADDR)'+
      ' left join SPR$STREET ST on (ST.CODE = SA.STREET)'+
      ' left join SPR$ETYPE SE on (SE.CODE = E.ETYPE)'+
      ' left join SPR$RTYPE SR on (SR.CODE = E.ERESULT)'+
      ' left join SPR$KONTRAGENT SK on (SK.CODE = E.KONTRAGENT)'+
      ' LEFT JOIN Reestr nr ON (nr.acCcode=e.acccode)'+
      ' left join SPR$USERS SU on (SU.CODE = E.USR)'+
      ' left join SPR$USERS SUR on (SUR.CODE = E.RUSR)'+
      ' WHERE '+
      ' @@where_clause% 1 = 1 @';
 InfoPanel.Caption:='Формируется отчет. Ждите....';
 Application.ProcessMessages;
 DS.Close;
 DS.SelectSQL.Text:=sql;
 DS.ParamByName('where_clause').SetDefMacroValue;
 kont:=cbb_kontr.Properties.Grid.FocusedRowIndex;
 if IsPrincipal.Checked then
  clause:=' E.KONTRAGENT='#39+
  VarToStr(cbb_kontr.Properties.Grid.DataController.Values[kont,0])+#39+' AND ';

 S:=#39+DateToStr(dt1.Date)+#39' and '#39+DateToStr(dt2.Date)+#39;
 if RType.ItemIndex=0 then
  clause:=clause+' e.sdate between '+S +' AND '
 else
 if RType.ItemIndex=1 then
  clause:=clause+' e.dactive between '+S+' AND '
 else clause:=clause+'( e.lasttime between '+S+' and e.eresult<>'#39#39') AND ';

 if IsCollector.Checked then
 begin
  collect:=cbb_collect.Properties.Grid.FocusedRowIndex;
  clause:=clause+' nr.USR='+
    VarToStr(cbb_collect.Properties.Grid.DataController.Values[collect,0])+' AND ';
 end;

 if clause<>'' then Delete(clause,Length(clause)-4,4);
 DS.ParamByName('where_clause').AsString:=clause;
 prShow(True);
 DS.CloseOpen(false);
 prShow(False);
 InfoPanel.Caption:='Отчет сформирован. Время формирования: '+
                    FormatDateTime('HH:NN:SS',Now-StartTime);
end;

procedure TEventRepForm.SetNote;
begin
 Note.Lines.Text:='';
 if DS.IsEmpty then Exit;
 if ActiveControl=CGrid then
  Note.Lines.Text:=D.FN('Note').AsString
 else
  Note.Lines.Text:=DS.FN('Note').AsString;
end;

procedure TEventRepForm.SourceDataChange(Sender: TObject; Field: TField);
begin
// SetNote;
 //MakeFullList;
end;

procedure TEventRepForm.v1CellClick(Sender: TcxCustomGridTableView;
  ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
  AShift: TShiftState; var AHandled: Boolean);
  var
    ARecord: TcxCustomGridRecord;
begin
  //если строка фильтра то выходим
  if ACellViewInfo.GridRecord is TcxGridFilterRow  then Exit;
   SetNote;
   MakeFullList;
end;

procedure TEventRepForm.v1KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
 // is TcxGridFilterRow  then Exit;

 if (Key=VK_UP) or (Key=VK_DOWN) then
 begin
  SetNote;
  MakeFullList;
 end;
end;

end.
